//获取应用实例
var app = getApp();
var FormCheckRule = {
    idCardRule1: /^[0-9]{14}([0-9]|X|x)$/,
    idCardRule2: /^[0-9]{17}([0-9]|X|x)$/,
    nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
    telRule: /^[1]{1}[0-9]{10}$/,
    certPlaceMessage: "请选择发证城市",
    certTypeMessage: "请选择办理类型",
    cardNbrNullMessage: "请输入驾驶证号！",
    cardNbrErrorMessage: "请输入正确的驾驶证号！",

    cardNameNullMessage: "请输入驾驶人姓名！",
    cardNameErrorMessage: "请输入正确的驾驶人姓名！",
    certPlaceNameNullMessage: "请选择签发城市！",
    certPlaceNameErrorMessage: "请选择正确的签发城市！",

    cellNumNullMessage: "请输入收件人电话！",
    cellNumErrorMessage: "请输入正确的收件人电话！",
    contactNameNullMessage: "请输入收件人姓名！",
    contactNameErrorMessage: "请输入正确的收件人姓名！",
    areaNameNullMessage: "请选择所在地区!",
    streetNullMessage: "请输入详细地址！",
    num: 0

};


Page({
    data: {
        area: "请选择所在地区",
        areaStyle: "color: #B2B2B2;font-size:34rpx",
        certPlaceStyle: "color: #B2B2B2;font-size:34rpx",
        certTypeStyle: "color: #B2B2B2;font-size:34rpx",
        cardNbrStyle: "",
        errorFocusName: "",
        num: 0,
        isNoticeShow: false,
        isAdvertShow: false,
        advertIconUrl: "",
        needInvoice: 0,
        agree: 0,
        isShowFootNav: true,
        certPlaceListShowed: false,
        certTypeListShowed: false,
        isCanScroll: true,
        certPlaceList: [],//办理城市
        certTypeList: [],//办理类别
        certPlaceText: FormCheckRule.certPlaceMessage,
        certPlaceCityId: "",
        certPlaceCityName: "",
        certPlaceProvinceId: "",
        certPlaceProvinceName: "",
        certTypeId: 0,
        certTypeName: FormCheckRule.certTypeMessage,
        handleDoc: "",
    },
    onShareAppMessage: function () {   //分享功能
        return {
            title: '驾驶证补换服务',
            desc: '驾驶证补换服务',
            path: '/pages/handle/handle'
        }
    },
    onLoad: function (options) {
        // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
        app.globalData.channelId = decodeURIComponent(options.scene)=='undefined'?'':decodeURIComponent(options.scene);
        console.log("channelId",app.globalData.channelId);
        var pageObj = this;

        var advertOpt = {   //请求广告
            url: app.globalData.host + "/wx/dc/ad.ajax",
            data: {},
            sucFn: function (result) {
                if (result.body != null) {
                    pageObj.setData({
                        isAdvertShow: true,
                        advertIconUrl: result.body.icon
                    });
                }
            }
        };
        app.ajax(advertOpt);
        
        var driverChangeHandleOpt = {   //业务办理条件
            url: app.globalData.host + "/wx/dc/qcbl.ajax",
            data: {},
            sucFn: function (result) {
                if (result.body || 1000 == result.code) {
                    pageObj.onCertDataGot(result.body);
                    if (null != page && "" != page.certPlaceCityId){
                        pageObj.setCertType(page.certPlaceCityId);
                    }
                }
            }
        };
        app.ajax(driverChangeHandleOpt);

        app.initAddress();
        if (app.globalData.openId != '' && app.globalData.openId != null && app.globalData.openId != 'null') {
            var opt2 = {
                url: app.globalData.host + "/wx/dc/list.ajax",
                data: {
                    'bizFlag': app.globalData.bizDoingFlag,
                    'orderType': app.globalData.orderType
                },
                sucFn: function (result) {
                    var num = "";
                    if (result.body.orderList.length != 0) {
                        num = result.body.orderList.length;
                    }
                    pageObj.setData({
                        "num": num
                    });
                }
            };
            app.ajax(opt2);
        } else {
            wx.login({//调用登录接口
                success: function (res) {
                    var opt = {//后台兑换openId
                        url: app.globalData.host + "/wx/dc/eo.ajax",
                        data: {
                            'code': res.code
                        },
                        showLoadFlag: "false",
                        sucFn: function (result) {
                            if (result.body.openId != '' && result.body.openId != null && result.body.openId != 'null') {
                                app.globalData.openId = result.body.openId;
                                var opt2 = {
                                    url: app.globalData.host + "/wx/dc/list.ajax",
                                    data: {
                                        'bizFlag': app.globalData.bizDoingFlag,
                                        'orderType': app.globalData.orderType
                                    },
                                    showLoadFlag: "false",
                                    sucFn: function (result) {
                                        var num = 0;
                                        if (result.body.orderList.length != 0) {
                                            num = result.body.orderList.length;
                                        }
                                        pageObj.setData({
                                            "num": num
                                        });
                                    }
                                };
                                app.ajax(opt2);
                            } else {
                                app.toastAuthFailModal();
                                return false;
                            }
                        }
                    };
                    app.ajax(opt);
                }
            });
        }


        var page = app.getStorageSync(app.globalData.cachePageKey);
        if (page != null && page != "") {
            this.setData({
                "cardNbr": page.cardNbr,
                "cardName": page.cardName,
                "certPlaceName": page.certPlaceName,
                "certPlaceCityId": page.certPlaceCityId,
                "agree": page.agree,
                "certPlaceText": page.certPlaceText,
                "certPlaceCityId": page.certPlaceCityId,
                "certPlaceCityName": page.certPlaceCityName,
                "certPlaceProvinceId": page.certPlaceProvinceId,
                "certPlaceProvinceName": page.certPlaceProvinceName,
                "certTypeId": page.certTypeId,
                "certTypeName": page.certTypeName,
                "handleDoc": page.handleDoc,
            });

            if (page.cardNbr != '' && page.cardNbr != null) {
                if (FormCheckRule.idCardRule1.test(page.cardNbr) && page.cardNbr.length == 15) {
                    this.setData({"cardNbrIconType": "success"});
                } else if (FormCheckRule.idCardRule2.test(page.cardNbr) && page.cardNbr.length == 18) {
                    this.setData({"cardNbrIconType": "success"});
                } else if (page.cardNbr.length > 0) {
                    this.setData({"cardNbrIconType": "error"});
                } else {
                    this.setData({"cardNbrIconType": ""});
                }
            }
            if (page.certPlaceText == "" || page.certPlaceText == FormCheckRule.certPlaceMessage) {
                this.setData({certPlaceStyle: "color: #B2B2B2;font-size:34rpx"});
            } else {
              this.setData({ certPlaceStyle: "color: #1A1A1A;font-size:34rpx"});
            }
            if (page.certTypeName == "" || page.certTypeName == FormCheckRule.certTypeMessage) {
              this.setData({ certTypeStyle: "color: #B2B2B2;font-size:34rpx"});
            } else {
              this.setData({ certTypeStyle: "color: #1A1A1A;font-size:34rpx"});
              pageObj.setCertType(page.certPlaceCityId);
            }

            if (page.cardName != '' && page.cardName != null) {
                if (FormCheckRule.nameRule.test(page.cardName)) {
                    this.setData({"cardNameIconType": "success"});
                } else if (page.cardName.length > 0) {
                    this.setData({"cardNameIconType": "error"});
                } else {
                    this.setData({"cardNameIconType": ""});
                }
            }


            if (page.address != null) {
                this.setData({
                    "area": page.area,
                    "areaStyle": "",
                    "address.street": page.address.street,
                    "address.provinceId": page.address.provinceId,
                    "address.cityId": page.address.cityId,
                    "address.countyId": page.address.countyId,
                    "address.provinceName": page.address.provinceName,
                    "address.cityName": page.address.cityName,
                    "address.countyName": page.address.countyName,
                    "address.cellNum": page.address.cellNum,
                    "address.contactName": page.address.contactName
                });
                if (page.address.contactName != '' && page.address.contactName != null) {
                    if (FormCheckRule.nameRule.test(page.address.contactName)) {
                        this.setData({"contactNameIconType": "success"});
                    } else if (page.address.contactName.length > 0) {
                        this.setData({"contactNameIconType": "error"});
                    } else {
                        this.setData({"contactNameIconType": ""});
                    }
                }

                if (page.address.cellNum != '' && page.address.cellNum != null) {
                    if (FormCheckRule.telRule.test(page.address.cellNum)) {
                        this.setData({"cellNumIconType": "success"});
                    } else if (page.address.cellNum.length > 0) {
                        this.setData({"cellNumIconType": "error"});
                    } else {
                        this.setData({"cellNumIconType": ""});
                    }
                }
                if (page.area == '请选择所在地区') {
                    this.setData({areaStyle: "color: #B2B2B2;font-size:34rpx"});
                } else {
                    this.setData({areaStyle: "color:#1a1a1a;font-size:34rpx"});
                }
            }
        }
    },
    onHide: function () {
        app.setStorageSync(app.globalData.cachePageKey, this.data);
    },
    onShow: function () {
        var page = app.getStorageSync(app.globalData.cachePageKey);
        this.setData({
            num: page.num
        });
        if (page.cardNbr == null) {
            this.setData({cardNbr: null, cardName: null, "cardNbrIconType": "", cardNameIconType: ""});
            this.setData({"cardNameIconType": ""});
        }
    },

    //底部切换页面方法
    toUrl:function (e) {
      var url = e.currentTarget.dataset.url;
      if(url!='/pages/handle/handle'){
	      app.setStorageSync(app.globalData.cachePageKey, this.data);
        if(url == ''){
          var res = {
            appid:app.globalData.appid,
            path: app.globalData.path,
            envVersion: app.globalData.envVersion
          }
          app.crossToUrl(res)
        }else {
          app.redirectTo({url: url});
        }
      }
    },

	  onCertDataGot: function (e) {
        this.setData({
            certPlaceList: e.cityBizList,
        });
        // var certPlaceListTmp = [{ provinceId: "1", provinceName: "广东", cityId: "10001", cityName: "广州", bizTypeList: [{ typeId: "20001", typeName: "类型1" }, { typeId: "20002", typeName: "类型2" }] }, { provinceId: "1", provinceName: "广东", cityId: "10002", cityName: "佛山", bizTypeList: [{ typeId: "20003", typeName: "类型3" }, { typeId: "20004", typeName: "类型4" }] }];
    },
    /*************************************************************
     ******************办理城市以及列表显示  开始*******************
     ************************************************************* */
    certPalceInput: function (e) {

        var id = e.currentTarget.id;
        if (id == "certPlaceNameView") {
            var that = this;
            setTimeout(function () {
                that.setData({
                    isCanScroll: false,
                    certPlaceListShowed: true,
                    isShowFootNav: !that.data.isShowFootNav
                });
            }, 100)
        }
    },

    //选择办理城市列表
    showCertPlaceList: function (e) {
        if (this.data.certPlaceCityId != e.target.dataset.cityid) {
            this.setData({
                certTypeName: FormCheckRule.certTypeMessage,
                certTypeStyle: "color: #B2B2B2;font-size:34rpx",
            });
        }
        this.setData({
            isCanScroll: true,
            certPlaceListShowed: false,

            certPlaceCityId: e.target.dataset.cityid,
            certPlaceCityName: e.target.dataset.cityname,
            certPlaceProvinceId: e.target.dataset.provinceid,
            certPlaceProvinceName: e.target.dataset.provincename,
            certPlaceStyle: "color: #1A1A1A;font-size:34rpx",
            certPlaceText: e.target.dataset.provincename + e.target.dataset.cityname,
            isShowFootNav: true,
        });
        this.setCertType(e.target.dataset.cityid);
    },

    setCertType: function (certPlaceCityId) {
        for (var i = 0; i < this.data.certPlaceList.length; i++) {
            if (certPlaceCityId == this.data.certPlaceList[i].licCityId) {
                var certTypeListTmp = this.data.certPlaceList[i].item;
                // var handleDocTmp = this.data.certPlaceList[i].item.needMaterial;
                this.setData({
                    certTypeList: certTypeListTmp,
                    // handleDoc: handleDocTmp,
                });
                break;
            }
        }
    },
    /*************************************************************
     ******************办理城市以及列表显示  结束*******************
     ************************************************************* */
    hideSelection: function () {
        this.setData({
            isCanScroll: true,
            certPlaceListShowed: false,
            certTypeListShowed: false,
            isShowFootNav: true
        });
    },
    /*************************************************************
     ******************办理类型以及列表显示  开始*******************
     ************************************************************* */
    certTypeInput: function (e) {
        if (this.data.certPlaceText == FormCheckRule.certPlaceMessage) {
            app.errorToast(FormCheckRule.certPlaceMessage);
            return;
        }
        if (null == this.data.certTypeList || 0 == this.data.certTypeList.length) {
            this.setCertType(e.target.dataset.cityid);
        }
        var id = e.currentTarget.id;
        if (id == "certTypeNameView") {
            var that = this;
            setTimeout(function () {
                that.setData({
                    isCanScroll: false,
                    certTypeListShowed: true,
                    isShowFootNav: false
                });
            }, 100)
        }
    },
    //选择列表
    showCertTypeList: function (e) {
      for (var i = 0; i < this.data.certTypeList.length;i++){
        var certTypeTmp = this.data.certTypeList[i];
        if (certTypeTmp.bizType == e.target.dataset.typeid){
          var materialTmp = certTypeTmp.needMaterial;
          this.setData({
            handleDoc: materialTmp,
             });
          break;
        }
      }
        this.setData({
            isCanScroll: true,
            certTypeListShowed: false,
            certTypeId: e.target.dataset.typeid,
            certTypeName: e.target.dataset.typename,
            isShowFootNav: true,
            certTypeStyle: "color: #1A1A1A;font-size:34rpx",
        });
    },
    /*************************************************************
     ******************办理类型以及列表显示  结束********************
     ************************************************************* */
    infoInput: function (e) {
        var id = e.currentTarget.id;
        var value = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
        if (id == "cardNbr") {
            value = value.substring(0, 18);
            this.setData({"cardNbr": value});
            if(value==''){
                this.setData({"cardNbrIconType": "success"});
            }else if (value.length == 15 && FormCheckRule.idCardRule1.test(value)) {
                this.setData({"cardNbrIconType": "success"});
            } else if (value.length == 18 && FormCheckRule.idCardRule2.test(value)) {
                this.setData({"cardNbrIconType": "success"});
            } else if (value.length > 0) {
                this.setData({"cardNbrIconType": "error"});
            } else {
                this.setData({"cardNbrIconType": ""});
            }

        } else if (id == "cardName") {
          this.setData({ "cardName": value});
            if(value==''){
                this.setData({"cardNameIconType": "success"});
            }else  if (FormCheckRule.nameRule.test(value)) {
                this.setData({"cardNameIconType": "success"});
            } else if (value.length > 0) {
                this.setData({"cardNameIconType": "error"});
            } else {
                this.setData({"cardNameIconType": ""});
            }

        } else if (id == "address.contactName") {
          this.setData({ "address.contactName": value});
            if(value==''){
                this.setData({"contactNameIconType": "success"});
            }else if (value.length > 0 && FormCheckRule.nameRule.test(value)) {
                this.setData({"contactNameIconType": "success"});
            } else if (value.length > 0) {
                this.setData({"contactNameIconType": "error"});
            } else {
                this.setData({"contactNameIconType": ""});
            }
        } else if (id == "address.cellNum") {
            value = value.substr(0, 11);
            this.setData({ "address.cellNum": value});
            if(value==''){
                this.setData({"cellNumIconType": "success"});
            }else if (FormCheckRule.telRule.test(value)) {
                this.setData({"cellNumIconType": "success"});
            } else if (value.length > 0) {
                this.setData({"cellNumIconType": "error"});
            } else {
                this.setData({"cellNumIconType": ""});
            }
        } else if (id == "address.street") {
          this.setData({ "address.street": value});
            if(value==''){
                this.setData({"streetIconType": "success"});
            }else if (value.length >= 5) {
                this.setData({"streetIconType": "success"});
            } else if (value != '' && value != null && value.length < 5) {
                this.setData({"streetIconType": "error"});
            } else {
                this.setData({"streetIconType": ""});
            }
        }
    },
    cardNbrBlur: function (e) {
        var value = e.detail.value;
        if (value != null && value != '') {
            this.setData({cardNbr: value.toUpperCase()});
        }
    },
    formSubmit: function (e) {
        var formData = e.detail.value;

        var cardNbr = formData.cardNbr;
        var cardName = formData.cardName;
        var cellNum = formData['address.cellNum'];
        var contactName = formData['address.contactName'];
        var street = formData['address.street'];
        var provinceId = formData['address.provinceId'];

        if (null == this.data.certPlaceText
            || FormCheckRule.certPlaceMessage == this.data.certPlaceText) {
            app.errorToast(FormCheckRule.certPlaceMessage);
            this.setData({
              errorScrollIntoViewName: "title_image",
            });            
            return false;
        }
        if (null == this.data.certTypeName
            || FormCheckRule.certTypeMessage == this.data.certTypeName) {
          this.setData({
            errorScrollIntoViewName: "title_image",
          });
            app.errorToast(FormCheckRule.certTypeMessage);
            return false;
        }

        var flag = app.check([
            {
                value: cardName,
                errorFocusName: "cardName",
                errorScrollIntoViewName: "certPlaceNameView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.cardNameNullMessage);
                        return false;
                    } else if (FormCheckRule.nameRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.cardNameErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: cardNbr,
                errorFocusName: "cardNbr",
                errorScrollIntoViewName: "cardNameView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.cardNbrNullMessage);
                        return false;
                    } else if (value.length == 15 && FormCheckRule.idCardRule1.test(value)) {
                        return true;
                    } else if (value.length == 18 && FormCheckRule.idCardRule2.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.cardNbrErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: contactName,
                errorFocusName: "contactName",
                errorScrollIntoViewName: "cardNbrView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.contactNameNullMessage);
                        return false;
                    } else if (FormCheckRule.nameRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.contactNameErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: cellNum,
                errorFocusName: "cellNum",
                errorScrollIntoViewName: "contactNameView",
                fn: function (value) {
                    if ('' == value) {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    } else if (FormCheckRule.telRule.test(value)) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.cellNumErrorMessage);
                        return false;
                    }
                }
            },
            {
                value: provinceId,
                errorFocusName: "provinceId",
                errorScrollIntoViewName: "cellNumView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if (value != '') {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.areaNameNullMessage);
                        return false
                    }
                }
            },
            {
                value: street,
                errorFocusName: "street",
                errorScrollIntoViewName: "areaView",
                rule: app.globalData.Rule.required,
                fn: function (value) {
                    if (value.length >= 5) {
                        return true;
                    } else {
                        app.errorToast(FormCheckRule.streetNullMessage);
                        return false
                    }
                }
            }
        ]);
        if (!flag) {
            return false;
        }
        if (app.globalData.openId == '' || app.globalData.openId == null || app.globalData.openId == 'null') {
            app.toastAuthFailModal();
            return false;
        }
        var param = formData;
        param['address.fullAddr'] = formData['address.provinceName'] + formData['address.cityName'] + formData['address.countyName'] + street;
        param['licCityId'] = formData['certPlaceCityId'];
        param['bizType'] = formData['certTypeId'];
        param['certTypeName'] = this.data.certTypeName;
        param['driverName'] = cardName;
        param['driverlicNbr'] = cardNbr;
        var opt = {
            url: app.globalData.host + "/wx/dc/handling.ajax",
            data: param,
            sucFn: function (result) {
                param['licFee'] = result.body.licFee;
                param['canUseCoupon'] = result.body.canUseCoupon;
                param['discountAmount'] = result.body.discountAmount;
                param['docList'] = result.body.docList;
                param['serviceFee'] = result.body.serviceFee;
                param['serviceFeeDesc'] = result.body.serviceFeeDesc;
                param['totalChargeFee'] = result.body.totalChargeFee;
                param['totalFee'] = result.body.totalFee;
                app.setStorageSync(app.globalData.cacheOrderResKey, param);
                app.navigateTo({url: '../payment/payment'});
            }
        };
        app.ajax(opt);
    },
    agreeTap: function (e) {
        this.setData({
            isNoticeShow: true,
            isShowFootNav: false
        });
    },
    checkTap: function (e) {
        var agree = e.target.dataset.agree;
        if (agree == 0) {
            agree = 1;
        } else {
            agree = 0;
        }
        this.setData({agree: agree});
    },
    noticeKnowTap: function (e) {
        this.setData({
            isNoticeShow: false,
            isShowFootNav: true
        });
    },
    areaTap: function (e) {
        this.setData({
            isAddressShow: true,
            isShowFootNav: false
        });
    },
    addressShowTap: function (e) {
        this.setData({
            isAddressShow: false,
            isShowFootNav: true
        });
    },
    bindAddressChange: function (e) {
        app.bindAddressChange(e);
    },
    confirmAddressTap: function (e) {
        var current_value = this.data.value;
        var provinceName = this.data.proviceData[current_value[0]].name;
        var cityName = this.data.cityData[current_value[1]].name;
        var countyName = "";
        if (this.data.districtData[current_value[2]].name != null) {
            countyName = this.data.districtData[current_value[2]].name;
        }
        this.setData({
            isShowFootNav: true,
            isAddressShow: false,
            areaStyle: "color:#1a1a1a;font-size:34rpx",
            area: provinceName + cityName + countyName,
            "address.provinceId": this.data.proviceData[current_value[0]].id,
            "address.cityId": this.data.cityData[current_value[1]].id,
            "address.countyId": this.data.districtData[current_value[2]].id,
            "address.provinceName": provinceName,
            "address.cityName": cityName,
            "address.countyName": countyName
        });
    },
    cancelAddressTap: function (e) {
        this.setData({
            isShowFootNav: true,
            isAddressShow: false
        });
    }
});
